package com.foreknow.controller;

import com.foreknow.bean.User;
import com.foreknow.service.UserService;
import com.foreknow.service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * 1.servlet:服务器端的应用程序
 * 2.重写doGet/doPost方法:
 *   这两个方法会根据前端的请求来调用
 *   如果前端发送的请求是get请求,(例如:<a>链接<a/>)就会自动调用Servlet中的doGet方法
 *   如果前端发送的是post请求,(例如:<form><form/>)就会自动调用Servlet中的doPost方法
 * 3.HttpServletRequest 请求对象
 * 4.HttpServletResponse 响应对象
 *
 */
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //服务器端向客户端响应的内容的类型
//        resp.setContentType("text/html;charset=utf-8");
        //获取PrintWriter打印流 作用是向网页写一些基本的信息
        PrintWriter out = resp.getWriter();
        out.println("<html>");
        out.println("<head>");
        out.println("<title>servlet</title>");
        out.println("</head>");
        out.println("<body>");
        out.println(new Date());
        out.println("</body>");
        out.println("</html>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.setContentType("text/html;charset=utf-8");
        //向网页响应内容
        PrintWriter out = resp.getWriter();
        //如何获取到session
        HttpSession session = req.getSession();
        //request对象中的其他方法测试
//        out.println("获取请求方法的名称:"+req.getMethod());
//        out.println("获取项目访问的Application Context的名称:"+req.getContextPath());
//        out.println("获取请求的URI地址:"+req.getRequestURI());
        //获取前端请求的参数 name="tom"&password=123456
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        UserService service = new UserServiceImpl();
        User user = service.isValidate(username,password);
        if (user != null){
            //向session对象中保存数据 request.setAttribute("user",user.getAdminName())  session.setAttribute("user",user.getAdminName())
            session.setAttribute("user",user.getAdminName());
//            out.println("<a href=''>查看所有留言</a>");
//            out.println(username+"--------"+password);
            //请求转发
            req.getRequestDispatcher("/manager?q=list").forward(req,resp);
            //重定向
//            resp.sendRedirect(req.getContextPath()+"/get");
            //重定向可以转发到栈外资源  resp.sendRedirect("www.baidu.com");
        }else {
            out.println("error......");
        }
    }
}









